// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/dwio/common/executor_barrier.h>

namespace kumo::pollux::dwio::common {
    namespace {
        class BarrierElement {
        public:
            BarrierElement(size_t &count, std::mutex &mutex, std::condition_variable &cv)
                : count_{count}, mutex_{&mutex}, cv_{cv} {
                std::lock_guard lock{*mutex_};
                ++count_;
            }

            BarrierElement(BarrierElement &&other) noexcept
                : count_{other.count_}, mutex_{other.mutex_}, cv_{other.cv_} {
                // Move away
                other.mutex_ = nullptr;
            }

            BarrierElement(const BarrierElement &other) = delete;

            BarrierElement &operator=(BarrierElement &&other) = delete;

            BarrierElement &operator=(const BarrierElement &other) = delete;

            ~BarrierElement() {
                // If this object wasn't moved away
                if (mutex_) {
                    std::lock_guard lock{*mutex_};
                    if (--count_ == 0) {
                        cv_.notify_all();
                    }
                }
            }

        private:
            size_t &count_;
            std::mutex *mutex_;
            std::condition_variable &cv_;
        };
    } // namespace

    auto ExecutorBarrier::wrapMethod(melon::Func f) {
        return [f = std::move(f),
                    this,
                    barrierElement = BarrierElement(count_, mutex_, cv_)]() mutable {
            try {
                f();
            } catch (...) {
                std::lock_guard lock{mutex_};
                if (!exception_.has_exception_ptr()) {
                    exception_ = melon::exception_wrapper(std::current_exception());
                }
            }
        };
    }

    void ExecutorBarrier::add(melon::Func f) {
        executor_->add(wrapMethod(std::move(f)));
    }

    void ExecutorBarrier::addWithPriority(melon::Func f, int8_t priority) {
        executor_->addWithPriority(wrapMethod(std::move(f)), priority);
    }
} // namespace kumo::pollux::dwio::common
